var userinfoPath = appPath + "/userinfo";
var userPath = appPath + "/user";

/**
 * 验证表单
 */
/*
function loadValidation(){
	rapidValidation = new Validation("userinfo_from", {
		immediate : true,
		borderCur : true,
		isShowIcon : true
	});
}*/

$(document).ready(function() {
	//loadValidation();
	initGrid();
	initDialog();
});

function initGrid() {
	$("#userinfo").anzeJqGrid({
		mark : "userInfo",
		pager : "#userinfoMask",
		heightOffset : [58, 400],
		widthOffset : [0, 0],
		sortname : "id",
		sortorder : "desc",
		buttons : [{sn : "0101010801"}, {sn : "0101010802"}, {sn : "0101010803"},
		           {set : [{sn : "0101010804"}, {sn : "0101010805"}, {sn : "0101010806"}]}, {sn : "0101010807"}],
		queryComponent : "#queryPanel",
		queryForm : "#query_form",
		getFilters : getFilters,
		onButtonsInited : function () {
			initButton();
		}
	});
	
	$("#roleList").jqGrid({
		datatype: "json", 
		mtype: "POST",
		//width:445,
		autowidth: true,
        rowNum : 999999999,
		height :220,
		colNames:["ID", "角色名称","权限标识", "角色描述"], //列配置,必须和下面的colModel数量匹配
		colModel:[{name:"id", index:"id", hidden:true, sortable:true},
		        {name:"name", index:"status", width:100, sortable:true},
				{name:"mark", index:"mark", width:150, sortable:true},
				{name:"description", index:"description", width:250, sortable:true}
				],
		shrinkToFit : false,
		viewrecords: true,
		multiselect: true,
		sortable:true,
	    sortname:'id',
	    sortorder:'desc',
	    toolbar: [false,"top"],
		jsonReader:{repeatitems : false}
	});
}

var $userinfo_from, $id, $username, $name, $age, $email;

function initDialog(){
	//初始化弹出框
	$("#dialog-form").tooltip();
	$userinfo_from = $("#userinfo_from");
	$id = $("#userinfo_from #id"); 
	$username = $("#userinfo_from #userName"); 
	$name = $("#userinfo_from #name");
	$age = $("#userinfo_from #age");
	$email= $("#userinfo_from #email");
}

function initButton() {
	jQuery("#0101010801").click(function() {
		$("#usernameEdit").removeAttr("disabled");
		$("#edit_dialog").anzeFormDialog({
			title : "新增",
			simpleMsg: true,
			width:650,
			height: 200,
			rules : {
				userName : {
					maxlength : 20,
					required : true,
					remote : {url : userPath + "/userNameExist", method : "GET"}
				},
				name : {
					maxlength : 20,
					required: true
				},
				age : {
					digits: true,
					maxlength : 3
				},
				email : {
					email : true
				}
			},
			messages : {
				userName : {
					maxlength : "最大长度20",
					required : "此字段必填",
					remote : "登录名称已存在"
				},
				name : {
					maxlength : "最大长度20",
					required : "此字段必填"
				},
				age : {
					digits : "请输入整数",
					maxlength : "最大长度3"
				},
				email : {
					email : "邮件格式错误"
				}
			},
			beforeSubmit: function ($form, options) {
				options.url = userinfoPath + "/add";
				return true;
			},
			onSuccess : function (data, textStatus, jqXHR) {
				if (data == "true") {
					$("#userinfo").anzeQuery();
					jQuery.anze.info('添加成功!');
				} else {
					jQuery.anze.error('添加失败!');
				}
			},
			onReset : function (validator) {
            	validator.resetForm();
            },
            open : function(validator){
                validator.resetForm();
            }
		}).dialog("open");
	});
	
	jQuery("#0101010802").button().click(function() {
		$("#usernameEdit").attr("disabled","disabled");
		var rowid = jQuery("#userinfo").jqGrid("getGridParam", "selarrrow");
		if (rowid == null || rowid.length == 0) {
			jQuery.anze.warn('请选择一条数据！');
			return;
		} else if(rowid.length > 1) {
			jQuery.anze.warn('只能选择一条数据！');
			return;
		}
		var row = $("#userinfo").jqGrid("getRowData", rowid);
		
		$("#edit_dialog").anzeFormDialog({
			title : "编辑",
			simpleMsg: true,
			width:650,
			height: 200,
			//hasResetButton: false,
			rules : {
				name : {
					maxlength : 20,
					required: true
				},
				age : {
					digits: true,
					maxlength : 3
				},
				email : {
					email : true
				}
			},
			messages : {
				name : {
					maxlength : "最大长度20",
					required : "此字段必填"
				},
				age : {
					digits : "请输入整数",
					maxlength : "最大长度3"
				},
				email : {
					email : "邮件格式错误"
				}
			},
			beforeSubmit: function ($form, options) {
				options.url = userinfoPath+"/"+rowid;
				options.data = {
					realName: $("#nameEdit").val(),
					_method: "PUT"
				};
				return true;
			},
			onSuccess : function (data, textStatus, jqXHR) {
				var msg = "";
				if("true" == data){
					jQuery.anze.info("用户编辑成功");
				} else{
					jQuery.anze.error("用户编辑失败");
				}
				$("#userinfo").anzeQuery();
			},
			onReset : function (validator) {
            	validator.resetForm();
            	initEdit(row);
            },
            open : function(validator){
                validator.resetForm();
        		initEdit(row);
            }
		}).dialog("open");
	});
	
	$("#0101010803").button().click(function(){
		var rowid = jQuery("#userinfo").jqGrid("getGridParam", "selarrrow");
		if (rowid == null || rowid.length == 0) {
			jQuery.anze.warn('请选择一条数据！');
			return;
		} else if(rowid.length > 1) {
			jQuery.anze.warn('只能选择一条数据！');
			return;
		}
		
		var row = $("#userinfo").jqGrid("getRowData", rowid);
		if (row.status == "9") {
			jQuery.anze.warn('该用户已弃用,不能授权!');
			return;
		}
		$("#authorize_dialog").anzeFormDialog({
			title: "授权",
			width:600,
			bindEnter:false,
			hasResetButton:false,//不显示重置按钮
			beforeSubmit: function ($form, options) {
				return authorize(rowid, options);
			}, 
			open: function(validator){
                validator.resetForm();
                initAuthorize(row);
            },
            onSuccess : function (data, textStatus, jqXHR) {
				$("#userinfo").anzeQuery();
				jQuery.anze.info("用户授权成功!"); 
			}
		}).dialog("open");
		$("#authorize_dialog").find(".resetWidth").css("width","350px")
		.find(".input").css("width","100%");
	});
	
	function initAuthorize(row){
		jQuery("#roleList").jqGrid('clearGridData');
		$("#usernameSpan").html(row.username);
		$("#statusSpan").html("0" == row.status ? "启用" : ("1" == row.status ? "禁用" : ("9" == row.status ? "弃用" : "冻结")));
		$.ajax({
			type:"POST",
			url: userPath +"/" + row.id + "/role",
			dataType: "json",
			success:function(data){
				var roles=data.roles;
				var userRole = data.userRole;
				var choosedRoles="";
				if(roles!=null && "" != roles){
					$("#roleList").anzeQuery({datatype: "local", data: roles});
				}
				if (null != userRole && "" != userRole) {
					for (var i = 0; i < userRole.length; i++) {
						jQuery("#roleList").jqGrid('setSelection', userRole[i].id, true);
						var isChoosed=false;
						if(roles!=null && "" != roles){
							for (var j = 0; j < roles.length; j++) {
								if(roles[j].id==userRole[i].id){
									isChoosed=true;
									break;
								}
							}
						}
						if(isChoosed){
							choosedRoles+="<span style='color:green'>"+userRole[i].name+"</span>，";
						}else{
							choosedRoles+=userRole[i].name+"，";
						}
					}
				}
				if(""!=choosedRoles){
					choosedRoles=choosedRoles.substring(0, choosedRoles.length-1);
				}
				$("#choosedRolesSpan").html(choosedRoles);
			},
			error: function(jqXHR, textStatus, errorThrown, handled) {
				if (!handled) {
					jQuery.anze.error('获取角色失败!');
				}
			}
		});
	}
	
	function authorize(id, options) {
		var roleIds = $("#roleList").jqGrid("getGridParam", "selarrrow");
//		if (roleIds.length <= 0) {
//			jQuery.anze.warn('请至少选择一个角色!');
//			return false;
//		}
		options.data = {"id":id.toString(), "roleIds":roleIds.toString()};
		options.url = userPath + "/authorize";
		options.type = "POST";
		return true;
	}
	
	$("#0101010804").button().click(function(){
		var rowid = $("#userinfo").jqGrid('getGridParam','selarrrow');
		if (rowid == null || rowid.length == 0) {
			jQuery.anze.warn('请选择一条数据！');
			return;
		}
		var row = $("#userinfo").jqGrid("getRowData", rowid);
		if (row.status == "9") {
			jQuery.anze.warn('该用户已弃用,不能启用!');
			return;
		}
		$.ajax({
			type:"POST",
			url: userPath +"/editStatus",
			dataType: "text",
			data:{"ids":rowid + "" , "status":"0"},
			success:function(responseText){
				if(responseText=="true"){
					jQuery.anze.info('启用成功!');
					$("#userinfo").anzeQuery();
				}else if(responseText=="false"){							
					jQuery.anze.error('启用失败!');
				}else{
					jQuery.anze.error(responseText);
				}
			},
			error: function(jqXHR, textStatus, errorThrown, handled) {
				if (!handled) {
					jQuery.anze.error('启用失败!');
				}
			}
		});
	});
	$("#0101010805").button().click(function(){
		 var rowid = $("#userinfo").jqGrid('getGridParam','selarrrow');
			if (rowid == null || rowid.length == 0) {
				jQuery.anze.warn('请选择一条数据！');
				return;
			}else if(rowid.length > 1) {
	            jQuery.anze.warn('只能选择一条数据！');
	            return;
	        }
			var row = $("#userinfo").jqGrid("getRowData", rowid);
			if (row.status == "9") {
				jQuery.anze.warn('该用户已弃用,不能停用!');
				return;
			}
	        $.anze.ajax({
				type:"POST",
				url: userPath +"/editStatus",
				dataType: "text",
				data:{"ids":rowid + "","status":"1"},
				success:function(data, textStatus, jqXHR){
					if(data == "true"){
						jQuery.anze.info('停用成功!');
					} else if(data == "false"){
						jQuery.anze.error('停用失败!');
					} else {
						jQuery.anze.error(data);
					}
	                $("#userinfo").anzeQuery();
				},
	            error: function(jqXHR, textStatus, errorThrown, handled) {
	                if (!handled) {
	                    jQuery.anze.error('停用失败!');
	                }
	            }
			});
	});
	$("#0101010806").button().click(function(){
		var rowid = $("#userinfo").jqGrid("getGridParam", "selarrrow");
		if (rowid == null || rowid.length == 0) {
			jQuery.anze.warn('请选择一条数据！');
			return;
		}else if(rowid.length > 1) {
            jQuery.anze.warn('只能选择一条数据！');
            return;
        }
		jQuery.anze.confirm("提示", "你确定要弃用该用户吗?", function (){
			$.anze.ajax({
				type:"POST",
				url: userPath +"/editStatus",
				dataType: "text",
				data:{"ids":rowid + "","status":"9"},
				success:function(data, textStatus, jqXHR){
	                jQuery.anze.info('弃用成功!');
	                $("#userinfo").anzeQuery();
				},
				error: function(jqXHR, textStatus, errorThrown, handled) {
					if (!handled) {
						jQuery.anze.error('弃用失败!');
					}
				}
			});
		});
	});
	$("#0101010807").button().click(function(){
		var rowid = $("#userinfo").jqGrid('getGridParam','selarrrow');
		if (rowid == null || rowid.length == 0) {
			jQuery.anze.warn('请选择一条数据！');
			return;
		} else if(rowid.length > 1) {
			jQuery.anze.warn('只能选择一条数据！');
			return;
		}
		var row = $("#userinfo").jqGrid("getRowData", rowid);
		if (row.status == "9") {
			jQuery.anze.warn('该用户已弃用,不能重置密码!');
			return;
		}
        $.anze.confirm("警告","是否确认重置所选操作员登录密码?",function(){
            $.ajax({
                type:"POST",
                url: userPath +"/"+rowid+"/resetPassWord",
                dataType: "text",
                success:function(responseText){
                    if(responseText=="true"){
                        jQuery.anze.info('重置密码成功!');
                    }else{
                        jQuery.anze.error('重置密码失败!');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown, handled) {
                    if (!handled) {
                        jQuery.anze.error(200,{herder:'提示',msg:'重置密码失败!'});
                    }
                }
            });
        });
	});
	
	//更新窗口的重置方法
	function initEdit(row){
		$("#userinfo_form").clearForm();
		$("#id").val(row.id);
		$("#usernameEdit").val(row.username); 
		$("#nameEdit").val(row.name);
		$("#ageEdit").val(row.age);
		$("#emailEdit").val(row.email);
	}
}

//查询
function getFilters() {
	var query_username = $("#query_form #username").val();
	var query_status = $("#query_form #status").val();
	query_username = query_username ? query_username.replace(/(^\s*)|(\s*$)/g, "") : "";
	var queryCondition ="{'groupOp':'AND','rules':[";
	if (!isSuper) {
		var condition = "{'field':'username','op':'ne','data':'superadmin'},";
		queryCondition = queryCondition.concat(condition);
	}
	if (query_username != "") {
		var condition = "{'field':'username','op':'cn','data':'"+ query_username +"'},";
		queryCondition = queryCondition.concat(condition);
	}
	if (query_status != ""){
		var condition = "{'field':'status','op':'eq','data':'"+ query_status +"'},";
		queryCondition = queryCondition.concat(condition);
	}
	if("," == queryCondition.charAt(queryCondition.length - 1)){
		queryCondition = queryCondition.substr(0, queryCondition.length - 1);
	}
	queryCondition = queryCondition.concat("]}");
	
	return queryCondition;
}
